package com.bw.controller;

import cn.hutool.core.lang.hash.Hash;
import com.alibaba.fastjson2.JSON;
import com.bw.domain.Role;
import com.bw.domain.TbMenu;
import com.bw.service.MenuService;
import com.bw.service.RoleService;
import com.bw.utils.MenuUtil;
import com.bw.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;

/**
 * @author bobo棒
 * @date 2025年03月13日 9:13
 */

@Controller
@RequestMapping("role")
public class RoleController {
    @Autowired
    RoleService roleService;
    @Autowired
    MenuService menuService;


    /**
     * 检查角色是否存在
     * @param roleName
     * @return
     */
    @ResponseBody
    @RequestMapping("checkRoleName")
    public R  checkRoleName(String roleName){
      Role role=  roleService.checkRoleName(roleName);
      //如果角色存在,则查询该角色拥有的菜单
        List<Integer> menuIds =null;
        HashMap<String, Object> map = new HashMap<>();
      if(role!=null){
         menuIds = roleService.getMenuIdsByRoleId(role.getId());
          map.put("roleId",role.getId());
          map.put("menuIds",menuIds);
      }


        return role!=null?R.OK(map):R.ERROR(500,"角色不存在");
    }

    /**
     * 添加角色并授权
     * @param role
     * @param menuIds
     * @return
     */
    @ResponseBody
    @RequestMapping("add")
    public R add(Role role,String menuIds){
     boolean b=  roleService.add(role,menuIds);
     return b?R.OK():R.ERROR(500,"操作失败");

    }

    /**
     * 进入角色添加
     *
     * @return
     */
    @RequestMapping("toAdd")
    public String toAdd(Model model) {
        //查询所有菜单
        List<TbMenu> allMenuList = menuService.list(null);
        //调用工具类

        List<TbMenu> treeMenuList = MenuUtil.treeMenus(allMenuList, null);
        model.addAttribute("treeMenuList", JSON.toJSON(treeMenuList));

        return "/role/add";

    }

    /**
     * 返回角色数据
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("list")
    public R list() {

        List<Role> roleList = roleService.list();

        return R.OK(roleList);

    }

    /**
     * 进入角色列表
     *
     * @return
     */
    @RequestMapping("tolist")
    public String tolist() {
        return "/role/list";

    }


}
